// Vidioplayer.cpp
#include "Vidioplayer.h"
#include "ui_Vidioplayer.h"
#include <QFileDialog>
#include <QMessageBox>

Vidioplayer::Vidioplayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Vidioplayer)
{
    ui->setupUi(this);

    // 初始化播放器和视频窗口
    pPlayer = new QMediaPlayer(this);
    videoWidget = new QVideoWidget(ui->video_widget);  // 正确创建视频窗口
    pPlayer->setVideoOutput(videoWidget);

    // 确保video_widget有布局
    if (!ui->video_widget->layout()) {
        ui->video_widget->setLayout(new QVBoxLayout());
    }
    ui->video_widget->layout()->addWidget(videoWidget);

    // 连接信号
    connect(pPlayer, &QMediaPlayer::durationChanged, this, [=](qint64 duration) {
        totalDuration = duration;
        setvalue(totalDuration, currentPosition);
    });

    connect(pPlayer, &QMediaPlayer::positionChanged, this, [=](qint64 pos) {
        currentPosition = pos;
        setvalue(totalDuration, currentPosition);
    });


}

Vidioplayer::~Vidioplayer()
{
    delete ui;
    // Qt对象会自动删除，不需要手动删除pPlayer和videoWidget
}

void Vidioplayer::setvalue(qint64 totalDuration, qint64 currentPosition) {
    if (totalDuration <= 0) return;
    int progress = static_cast<int>((currentPosition * 100) / totalDuration);
    ui->time_hor->setValue(progress);
}

void Vidioplayer::on_openbtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "请选择视频文件",
           "D:/testvideo",
           "视频文件(*.mp4 *.flv);;所有文件(*.*)");

    if (fileName.isEmpty()) return;

    // 重置播放器
    pPlayer->stop();
    pPlayer->setMedia(QUrl::fromLocalFile(fileName));
}

void Vidioplayer::on_startbtn_clicked()
{
    if (pPlayer->media().isNull()) {
        QMessageBox::warning(this, "警告", "请先打开视频文件");
        return;
    }
    pPlayer->play();
}

void Vidioplayer::on_overbtn_clicked()
{
    pPlayer->stop();
}

void Vidioplayer::on_pushButton_clicked()
{
    pPlayer->stop();
    emit showMenu();
}
